package com.zhy.generator.codegen.mybatis.xmlmapper.element;

import com.zhy.generator.codegen.api.IntrospectedColumn;
import com.zhy.generator.codegen.dom.xml.Attribute;
import com.zhy.generator.codegen.dom.xml.TextElement;
import com.zhy.generator.codegen.dom.xml.XmlElement;
import com.zhy.generator.codegen.mybatis.MyBatis3FormattingUtilities;
import com.zhy.generator.codegen.mybatis.xmlmapper.XmlElementIdConstant;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author Jeff Butler
 */
public class SelectByPrimaryKeyElementGenerator extends AbstractXmlElementGenerator {

    public SelectByPrimaryKeyElementGenerator() {
        super();
    }

    @Override
    public void addElements(XmlElement parentElement) {
        XmlElement answer = new XmlElement("select"); //$NON-NLS-1$
        answer.addAttribute(new Attribute("id", XmlElementIdConstant.SELECT_BY_PRIMARYKEY));
        answer.addAttribute(new Attribute("resultType", introspectedTable.getBaseRecordType()));
        String parameterType;
        if (introspectedTable.getRules().generatePrimaryKeyClass()) {
            parameterType = introspectedTable.getPrimaryKeyType();
        } else {
            if (introspectedTable.getPrimaryKeyColumns().size() > 1) {
                parameterType = "map"; //$NON-NLS-1$
            } else {
                parameterType = introspectedTable.getPrimaryKeyColumns().get(0).getFullyQualifiedJavaType().toString();
            }
        }
        answer.addAttribute(new Attribute("parameterType",parameterType));
        StringBuilder sb = new StringBuilder();

        sb.append("select * from "); //$NON-NLS-1$
        sb.append(introspectedTable.getIntrospectedTableName());
        sb.append(" where ");

        List<IntrospectedColumn> primaryKeyColumns = introspectedTable.getPrimaryKeyColumns();
        if(CollectionUtils.isEmpty(primaryKeyColumns)){
            return;
        }
        sb.append(MyBatis3FormattingUtilities.getAliasedEscapedColumnName(primaryKeyColumns.get(0)));
        sb.append(" = #{pkid}");

        answer.addElement(new TextElement(sb.toString()));

        if (context.getPlugins().sqlMapSelectByPrimaryKeyElementGenerated(answer,introspectedTable)) {
            parentElement.addElement(answer);
        }
    }
}
